package main

import (
	"fmt"
	//"io/ioutil"

	"ktvserver/config"
	"ktvserver/ktvcmdserver"
	"ktvserver/ktvdownloadserver"
	"ktvserver/ktvutil"
	"ktvserver/ktvutil/videopath"
	"ktvserver/webserver"
	"log"
	"os"
	//	"strings"
	//	"time"
)

const (
	server_name = "KtvDownloadServer"
	server_desc = "KtvDownloadServer service"
	version     = "1.0.1"
)

var (
	serverEvent chan int
)

func main() {

	serverMain()

}

func serverMain() {

	Usage()

	// 初始化服务
	ktvutil.InitApplication()

	// 启动服务
	ktvutil.StartMainFunc(
		ktvutil.GetNTServiceName(), // NT服务名称
		server_desc,                // NT服务描述
		StartServer,                // 启动服务的函数
		StopServer,                 // 停止服务的函数
	)

}

// 启动服务
func StartServer() {

	serverEvent = make(chan int)

	port := ktvutil.GetDownloadServerPort()

	log.Printf("KtvDownloadServer port = %d\n", port)

	// 显示互联网IP地址
	internetIP := ktvutil.GetInternetAddress()
	if len(internetIP) > 0 {
		log.Printf("internet ip = %s\n", internetIP)
	} else {
		log.Printf("internet is disconnected\n")
	}

	// 初始化视频路径
	videopath.InitSongVideoPath()

	//strNotice, _ := ktvutil.LoadNoticeText(1)
	//log.Printf("notice=%s", strNotice)

	// 启动UDP服务
	go ktvcmdserver.StartServerByPort(port)

	// 启动TCP服务
	go ktvdownloadserver.StartServerByPort(port)

	// 启动web服务
	if config.EnableWebServer {
		webserver_port := ktvutil.GetWebServerPort()
		go webserver.StartServerByPort(webserver_port)
	}

	// 监听文件修改
	go EnableWatherSystemDirectory()

	// 进入阻塞，等待停止信号
	<-serverEvent

}

// 停止服务
func StopServer() {

	ktvdownloadserver.StopServer()
	ktvcmdserver.StopServer()

	myWatcherDone <- true

	// 发出停止信号
	serverEvent <- 1

}

func Usage() {

	fmt.Printf("Ktv Download Server %s\n", config.Version)
	fmt.Println("----------------------www.sysdvod.cn-------------------------")
	fmt.Printf("%s -i			install nt service\n", os.Args[0])
	fmt.Printf("%s -u			uninstall nt service\n", os.Args[0])
	fmt.Printf("%s -start 		start nt service\n", os.Args[0])
	fmt.Printf("%s -Stop 		stop nt service\n", os.Args[0])
	fmt.Println("-------------------------------------------------------------")

}
